﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Configuration;

using Think.Lenovo.Com.Models;
using Think.Lenovo.Com.Models.Users;
using Think.Lenovo.Com.DataAccess;
using Think.Lenovo.Com.DataAccess.User;
using Think.Lenovo.Com.Common;
using System.Configuration;

namespace Think.Lenovo.Com.Controllers
{
    public class RegisterController : Controller
    {
        /// <summary>
        /// 注册页面第一步
        /// </summary>
        /// <returns></returns>
        public ActionResult ViewRegisterUserStep1()
        {
            return View("/Views/ViewRegisterUserStep1.cshtml");
        }
        /// <summary>
        /// 注册第一步
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public void RegisterUserStep1(UserModel model)
        {
            LinkedList<String> errors = new LinkedList<string>();
            #region//step 1 验证
            if (String.IsNullOrEmpty(model.UserName))
            {
                errors.AddLast("用户名不能为空");
            }
            if (String.IsNullOrEmpty(model.UserPassword) || String.IsNullOrEmpty(Request["UserPassword2"]))
            {
                errors.AddLast("密码不能为空!");
            }
            else if (model.UserPassword != Request["UserPassword2"])
            {
                errors.AddLast("两次输入的密码不一致");
            }
            if (String.IsNullOrEmpty(Request["IsAgree"]))
            {
                errors.AddLast("您不同意注册协议");
            }
            #endregion
            try
            {
                #region//插入数据
                if (errors.Count < 1)
                {
                    User u = new User();
                    model.UserRoleId = 4;
                    model.UserLevelId = 4;
                    model.UserStateId = 1;
                    long id = u.AddUser(model);
                    if (id > 0)
                    {
                        ViewBag.UserId = id;
                        Response.Write("<script type=\"text/javascript\">");
                        Response.Write("var isOk = confirm(\"注册成功,点击确定补全您的基本资料!\");");
                        Response.Write("if(isOk)");
                        Response.Write("{");
                        Response.Write("window.location='/Register/ViewRegisterUserStep2/" + id + "';");
                        Response.Write("}");
                        Response.Write("else");
                        Response.Write("{");
                        Response.Write("window.location='/home/userhome.aspx';");
                        Response.Write("}");
                        Response.Write("</script>");
                    }
                    else
                    {
                        //提示注册失败,及失败原因
                        User user = new DataAccess.User.User();
                        ViewUserModel um = user.GetUser(model.UserName);
                        if (um != null && um.Id > 0)
                        {
                            Response.Write("<script type=\"text/javascript\">");
                            Response.Write("alert('用户名已存在,请您换一个用户名试试!');");
                            Response.Write("history.go(-1);");
                            Response.Write("</script>");
                        }
                    }
                }
                else
                {
                    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    String json = serializer.Serialize(errors);
                    Response.Write("<script type=\"text/javascript\">");
                    Response.Write("alert('" + json + "');");
                    Response.Write("history.go(-1);");
                    Response.Write("</script>");
                }
                #endregion
            }
            catch (Exception e)
            {
                String logFolder = WebConfigurationManager.AppSettings["LogRoot"];
                Log.RecordLog(logFolder, e);
                Response.Write("<script type=\"text/javascript\">");
                Response.Write("alert('参数错误 x1024s');");
                Response.Write("</script>");
            }
        }

        /// <summary>
        /// 注册页面第二步
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ViewRegisterUserStep2(int id)
        {
            ViewBag.UserId = id;

            #region//step 1.公司类型

            CompanyType ct = new CompanyType();
            LinkedList<CompanyTypeModel> comTypes = ct.GetCompanyTypeModels();
            List<SelectListItem> comTypeList = new List<SelectListItem>();
            SelectListItem first = new SelectListItem();
            first.Value = "";
            first.Text = "- 请选择 -";
            comTypeList.Add(first);
            foreach (CompanyTypeModel m in comTypes)
            {
                SelectListItem sli = new SelectListItem();
                sli.Text = m.CompanyTypeName;
                sli.Value = m.Id.ToString();
                comTypeList.Add(sli);
            }
            ViewBag.CompanyType = comTypeList;
            #endregion

            #region//step 2.公司性质

            CompanyProperty cp = new CompanyProperty();
            LinkedList<CompanyPropertyModel> comPropertyModels = cp.GetPropertyModels();
            List<SelectListItem> comPropertyList = new List<SelectListItem>();
            first = new SelectListItem();
            first.Value = "";
            first.Text = "- 请选择 -";
            comPropertyList.Add(first);
            foreach (CompanyPropertyModel m in comPropertyModels)
            {
                SelectListItem sli = new SelectListItem();
                sli.Text = m.CompanyProperty;
                sli.Value = m.Id.ToString();
                comPropertyList.Add(sli);
            }
            ViewBag.CompanyProperty = comPropertyList;
            #endregion

            return View("/Views/ViewRegisterUserStep2.cshtml");
        }

        public void RegisterUserStep2(UserInfoModel model)
        {
            LinkedList<String> errors = new LinkedList<string>();
            #region//验证
            #region//用户id
            {
                int i;
                if (!Int32.TryParse(model.UserId.ToString(), out i))
                {
                    errors.AddLast("用户id不能为空");
                }
            }
            #endregion
            #region//公司名称
            if (String.IsNullOrEmpty(model.CompanyName) || model.CompanyName.Trim().Length == 0)
            {
                errors.AddLast("公司名称不能为空!");
            }
            else
            {
                model.CompanyName = model.CompanyName.Trim();
            }
            #endregion
            #region//联系人真实姓名
            if (String.IsNullOrEmpty(model.RealName) || model.RealName.Trim().Length == 0)
            {
                errors.AddLast("联系人真实姓名不能为空");
            }
            else
            {
                model.RealName = model.RealName.Trim();
            }
            #endregion
            #region//公司地址
            if (String.IsNullOrEmpty(model.CompanyAddress) || model.CompanyAddress.Trim().Length == 0)
            {
                errors.AddLast("公司地址不能为空");
            }
            else
            {
                model.CompanyAddress = model.CompanyAddress.Trim();
            }
            #endregion
            #region//公司所属区域
            if (model.CompanyProvinceId < 1)
            {
                errors.AddLast("公司所属省份必填");
            }
            if (model.CompanyCityId < 1)
            {
                errors.AddLast("公司所属城市必填");
            }
            #endregion
            #region//公司Email
            if (String.IsNullOrEmpty(model.CompanyEmail) || model.CompanyEmail.Trim().Length == 0)
            {
                errors.AddLast("公司Email不能为空");
            }
            else
            {
                model.CompanyEmail = model.CompanyEmail.Trim();
            }
            #endregion
            #region//公司电话
            if (String.IsNullOrEmpty(model.CompanyTel) || model.CompanyTel.Trim().Length == 0)
            {
                errors.AddLast("公司电话不能为空");
            }
            else
            {
                model.CompanyTel = model.CompanyTel.Trim();
            }
            #endregion
            #region//联系人电话
            if (String.IsNullOrEmpty(model.UserPhoneNumber) || model.UserPhoneNumber.Trim().Length == 0)
            {
                errors.AddLast("联系人电话不能为空");
            }
            else
            {
                model.UserPhoneNumber = model.UserPhoneNumber.Trim();
            }
            #endregion
            #region//公司注册日期
            {
                DateTime dt = DateTime.Now;
                if (!DateTime.TryParse(model.CompanyRegisteDate.ToString(), out dt))
                {
                    errors.AddLast("公司注册日期不是一个日期格式");
                }
            }
            #endregion
            #region//公司类型
            {
                int i;
                if (!Int32.TryParse(model.CompanyType.ToString(), out i))
                {
                    errors.AddLast("必须选择公司类型");
                }
                else if (i < 1)
                {
                    errors.AddLast("必须选择公司类型");
                }
            }
            #endregion

            #endregion
            if (errors.Count > 0)
            {
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                String s = serializer.Serialize(errors);
                Response.Write("<script type='text/javascript'>");
                Response.Write("alert('" + s + "');");
                Response.Write("history.go(-1);");
                Response.Write("</script>");
                return;
            }
            else
            {
                try
                {
                    UserInfo ui = new UserInfo();
                    model.CompanyGrade = 50;
                    RegionInfo regionInfo = new RegionInfo();
                    model.CompanyRegion = regionInfo.GetBigAreaByProvinceId(model.CompanyProvinceId).Id;
                    long i = ui.AddUserInfo(model);
                    if (i > 0)
                    {
                        User u = new DataAccess.User.User();
                        UserModel um = u.GetUser(model.UserId);
                        ViewUserModel vum = u.GetUser(um.UserName, um.UserPassword, false);
                        Session["User"] = vum;
                        Response.Write("<script type='text/javascript'>");
                        Response.Write("alert('注册成功!');");
                        Response.Write("window.location='/Register/ViewRegisterUserStep3/" + model.UserId + "';");
                        Response.Write("</script>");
                        return;
                    }
                    else
                    {
                        StringBuilder js = new StringBuilder();
                        js.Append("<script type='text/javascript'>")
                            .Append("alert('注册失败,点击确定检查您的填写资料是否正确!');")
                            .Append("history.go(-1);")
                            .Append("</script>");
                        return;
                    }
                }
                catch (Exception e)
                {
                    String logFolder = WebConfigurationManager.AppSettings["LogRoot"];
                    e.Source += "注册用户时,发生了异常";
                    Log.RecordLog(logFolder, e);

                    #region//查看是不是 用户名已存在或者是邮箱已存在
                    User ur = new User();
                    ViewUserModel vum = ur.GetUser(model.CompanyEmail);
                    #endregion
                    StringBuilder js = new StringBuilder();
                    js.Append("<script type='text/javascript'>");
                    if (vum.Id > 0)
                    {
                        js.Append("alert('注册失败,公司邮箱已被别的公司占用!');");
                    }
                    else
                    {
                        js.Append("alert('注册失败!');");
                    }
                    js.Append("history.go(-1);")
                    .Append("</script>");
                    Response.Write(js.ToString());
                }
            }
        }

        /// <summary>
        /// 用户注册第三步页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ViewRegisterUserStep3(int id)
        {
            ViewBag.UserId = id;
            return View("/Views/ViewRegisterUserStep3.cshtml");
        }
    }
}
